/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.weiresearch.tags;

import com.opensymphony.xwork2.ActionSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author cgqhs
 */
public class InterestsTagAction extends ActionSupport {

    public String sinaUid;//对比账号uid

    public String name = "未知用户";//用户名
    public String age = "未知";//年龄
    public String livingPlace = "未知";//居住地
    public String incomeRange = "未知";//收入
    public String lottery  = "未知";//抽奖信息
    public String lotteryRate = "0";//抽奖贴率
    public List<Keywords> keywords = new ArrayList<Keywords>();//关键字
    public List<String> activeTime = new ArrayList<String>();//活跃时间
    public List<String> category = new ArrayList<String>();//分类
    public List<String> toAt = new ArrayList<String>();//经常@的人
    public List<Ads> adsURL = new ArrayList<Ads>();//推荐商铺列表

    public String getSinaUid() {
        return sinaUid;
    }

    public void setSinaUid(String sinaUid) {
        this.sinaUid = sinaUid;
    }

    public List<String> getActiveTime() {
        return activeTime;
    }

    public void setActiveTime(List<String> activeTime) {
        this.activeTime = activeTime;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public List<String> getCategory() {
        return category;
    }

    public void setCategory(List<String> category) {
        this.category = category;
    }

    public String getIncomeRange() {
        return incomeRange;
    }

    public void setIncomeRange(String incomeRange) {
        this.incomeRange = incomeRange;
    }

    public List<Keywords> getKeywords() {
        return keywords;
    }

    public List<String> getToAt() {
        return toAt;
    }

    public void setToAt(List<String> toAt) {
        this.toAt = toAt;
    }

    public void setKeywords(List<Keywords> keywords) {
        this.keywords = keywords;
    }

    public String getLivingPlace() {
        return livingPlace;
    }

    public void setLivingPlace(String livingPlace) {
        this.livingPlace = livingPlace;
    }

    public String getLottery() {
        return lottery;
    }

    public void setLottery(String lottery) {
        this.lottery = lottery;
    }

    public String getLotteryRate() {
        return lotteryRate;
    }

    public void setLotteryRate(String lotteryRate) {
        this.lotteryRate = lotteryRate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Ads> getAdsURL() {
        return adsURL;
    }

    public void setAdsURL(List<Ads> adsURL) {
        this.adsURL = adsURL;
    }

    @Override
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        String access_token = (String)request.getSession().getAttribute("access_token");//access_token
        String uid = (String)request.getSession().getAttribute("sinaUid");//sina user uid
        String weire_access_token = (String)request.getSession().getAttribute("weire_access_token");//oauth access_token of weiresearch

        String tencent_token = (String)request.getSession().getAttribute("tencent_token");

        if((access_token != null&&uid != null)||(tencent_token != null)){
            //keywords 取得广告内容的参数
            String keywords = "";
            //category 取得广告内容的参数
            String categoryWords = "";

            String tagURL = "http://202.85.221.51:30080/Interestgraph/tag?vpuid=1109&token="+access_token+"&uid="+uid+"&weiresearch_"+weire_access_token;
                    //"http://localhost:20080/graph/tag?vpuid=1002&token="+access_token+"&uid="+uid+"&weiresearch_"+weire_access_token;
            if(sinaUid != null){
                tagURL = "http://202.85.221.51:30080/Interestgraph/tag?vpuid=1109&token="+access_token+"&uid="+sinaUid+"&weiresearch_"+weire_access_token;
                        //"http://localhost:20080/graph/tag?vpuid=1002&token="+access_token+"&uid="+sinaUid+"&weiresearch_"+weire_access_token;
            }

            //qq账号登陆情况
            String openid = null;
            if(tencent_token != null){
                tagURL = "http://202.85.221.51:30080/Interestgraph/tag?vpuid=1109&token="+ tencent_token +"&domain=qq&weiresearch_" + weire_access_token;
            }

            Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, tagURL);
            String responseContent = this._sendHTTPGet(tagURL, null);
            Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, responseContent);
            if(responseContent == null){
            }
            //tag信息json
            JSONObject interests = new JSONObject(responseContent);
            //用户信息
            if(interests.has("name")){
                this.name = interests.getString("name");
            }
            if(interests.has("age")){
                try{
                    if(interests.getInt("age") == 14){
                        this.age = "--" + "岁";
                    }else {
                        this.age = interests.getString("age") + "岁";
                    }
                }catch(Exception e){
                    Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, null, e);
                    this.age = "--" + "岁";
                }
            }
            if(interests.has("income")){
                try{
                    this.incomeRange = interests.getString("income");
                    switch (Integer.parseInt(incomeRange)) {
                        case 6: this.incomeRange = "6万以下";break;
                        case 15: this.incomeRange = "6~15万";break;
                        case 30: this.incomeRange = "15~30万";break;
                        case 31: this.incomeRange = "30万以上";break;
                        default: this.incomeRange = "未知";
                    };
                }catch(Exception e){
                    Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, null, e);
                }
            }
            if(interests.has("livingplace")){
                this.livingPlace = interests.getString("livingplace");
                this.livingPlace.replaceAll(" ", "&nbsp;");
            }
            if(interests.has("couponRate")){
                this.lotteryRate = interests.getString("couponRate");
                try{
                    int rate = Integer.parseInt(lotteryRate);
                    if(rate > 20){
                        this.lottery = "酷爱抽奖";
                    }else {
                        this.lottery = "很少抽奖";
                    }
                }catch(Exception e){
                    Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, null, e);
                }
            }
            //关键字信息
            if(interests.has("words")){
                JSONArray words = interests.getJSONArray("words");
                for(int i = 0; i < words.length(); i++){
                    JSONObject item = words.getJSONObject(i);
                    String word = item.getString("word");
                    keywords += word;
                    if(i != words.length()-1){
                        keywords += ",";
                    }
                    String mention = item.getString("mention");
                    float score = Float.parseFloat(item.getString("emotion"));
                    List<String> emotions = this.getEmotions(score);
                    this.keywords.add(new Keywords(word, mention, emotions));
                }
            }
            //活跃时间
            if(interests.has("activehours")){
                JSONArray activehours = interests.getJSONArray("activehours");
                int topScore = -1;
                int secScore = -1;
                int indexT = -1;
                int indexS = -1;
                for(int i = 0; i < activehours.length(); i++){
                    JSONObject item = activehours.getJSONObject(i);
                    int score = Integer.parseInt(item.getString("score"));
                    if(score >= topScore){
                        indexS = indexT;
                        secScore = topScore;
                        indexT = i;
                        topScore = score;
                    }else if(score >= secScore) {
                        indexS = i;
                        secScore = score;
                    }
                }
                if(indexT >= 0)
                    this.activeTime.add(activehours.getJSONObject(indexT).getString("hour")+"时 ");
                if(indexS >= 0)
                    this.activeTime.add(activehours.getJSONObject(indexS).getString("hour")+"时 ");
            }
            //@统计信息
            if(interests.has("contacts")){
                JSONArray words = interests.getJSONArray("contacts");
                for(int i = 0; i < words.length(); i++){
                    JSONObject item = words.getJSONObject(i);
                    String contact = item.getString("contact")+" ";
                    this.toAt.add(contact);
                }
            }
            //ad属性推荐广告
            if(interests.has("ad")){
                String ads = interests.getString("ad");
                if(ads.indexOf("http") >= 0){
                    this.adsURL.add(new Ads("优先广告",ads));
                }
            }
            //分类信息
            if(interests.has("categories")){
                JSONArray categories = interests.getJSONArray("categories");
                for(int i = 0; i < categories.length(); i++){
                    JSONObject item = categories.getJSONObject(i);
                    
                    String categoryI = item.getString("category");
                    this.category.add(categoryI+"  ");
                    if(categoryWords.length() > 0){
                        categoryWords += ",";
                    }
                    categoryWords += categoryI;
                }
            }
            //suggestion 推荐
            String kw = "";
            if(categoryWords.isEmpty() || keywords.isEmpty()){
                kw = categoryWords + keywords;
            }else {
                kw = categoryWords + "," + keywords;
            }
            String keywordsURL = "http://202.85.221.51:30080/Interestgraph/resources/suggestions?weiresearch_"+weire_access_token+"&weiresearch_oauth_id=demo&keyword="+URLEncoder.encode(kw, "UTF-8");
            //String keywordsURL = "http://localhost:20080/graph/resources/suggestions?weiresearch_"+weire_access_token+"&weiresearch_oauth_id=test&keyword="+URLEncoder.encode(keywords, "UTF-8");
            String suggestions = this._sendHTTPGet(keywordsURL,"json");
            //keywords array
            String[] keywordList = keywords.split(",");
            //category words array
            String[] categoryWordList = categoryWords.split(",");
            try{
                JSONObject suggestionObj = new JSONObject(suggestions);
                JSONArray suggestion = suggestionObj.getJSONArray("suggestion");
                //keywords ads'url map
                Map adsMap = new HashMap();
                for(int i = 0; i < suggestion.length(); i++){
                    JSONObject item = suggestion.getJSONObject(i);
                    String content = item.getString("content");
                    String word = item.getString("keyword");
                    //this.adsURL.add(content);
                    adsMap.put(word, content);
                }
                for(int i = 0; i < keywordList.length; i++) {
                    if(adsMap.containsKey(keywordList[i])){
                        this.adsURL.add(new Ads("关键词推荐",(String)adsMap.get(keywordList[i])));
                    }
                }
                for(int i = 0; i < categoryWordList.length; i++) {
                    if(adsMap.containsKey(categoryWordList[i])){
                        this.adsURL.add(new Ads("分类推荐",(String)adsMap.get(categoryWordList[i])));
                    }
                }
            }catch(Exception e) {
                Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, null, e);
            }
        }else {
            return "tologin";
        }
        return SUCCESS;
    }

    private String _sendHTTPGet(String urlStr, String type) {
        URLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = url.openConnection();

            if(type != null&&type.equalsIgnoreCase("json")){
                conn.setRequestProperty("Accept", "application/json");
            }
            conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            Logger.getLogger(InterestsTagAction.class.getName()).log(Level.INFO, sb.toString());
            return sb.toString();
        } catch (Exception ex) {
            Logger.getLogger(InterestsTagAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "{\"errorDescription\":\"读取数据出错！\"}";
    }

    private String readContentFromGet() throws IOException {

        String getURL = "http://z.alimama.com/alimama.php?i=mm_33132458_3409344_10998891&w=950&h=90&re=1600x900&cah=852&caw=1600&ccd=24&ctz=8&chl=3&cja=0&cpl=18&cmm=28&cf=11.4&cg=5887525c20c8179189d8e5e8e026fcdb&ac=8054&pro=103842904&cas=pro&cbh=37&cbw=1584&sx=0&sy=80&refpos=,a,null&t=2&pf=1&p4p_ai=1&dx=1&iss=0&u=http%3A%2F%2Fwww.weiresearch.com%3A40080%2Fweiresearch%2FinterestsTag.jsp&k=&tt=WeiResearch.com&r=&fu=-1&pageid=7fb3d94ecbd3c96ee989659c3569e9a5";

        URL getUrl = new URL(getURL);

        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
        connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        //connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        connection.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Cookie", "cna=/D8VCR79SxsCAcOodnvnMcJd; lzstat_uv=3555851548479399631|700373@390770@359586@731961@1774292@2852791@1150438@633924; wwwtaobaocomsupport=743; cookie1=aaf56206db0608c52413c384dfa1c585; cookie10=zqLI8A%3D%3D; cookie3=eGlhemhlbnl1QHdlaXJlc2VhcmNoLmNvbQ%3D%3D; alimamapwag=TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgNi4xOyBXT1c2NDsgcnY6MTYuMCkgR2Vja28vMjAxMDAxMDEgRmlyZWZveC8xNi4w; login=W5iHLLyFOGW7aA%3D%3D; cookie2=MzMxMzI0NTg%3D; alimamapw=FiBxHXcFEXpZQHBUbFFSVQcGAwEBW1cCUA9UBAcHVFJaAVRTAFEACwcCBQ0C; v=0; _tb_token_=b3fb4b65b336; tlut=UoLZXeVqqF302g%3D%3D; lzstat_ss=1891694062_0_1351606612_700373|618673956_0_1351599583_390770|1422186898_0_1351599583_359586|3685690911_2_1351597674_731961|1734401391_67_1351600520_1774292|2393894984_2_1351600535_2852791|2869135852_0_1351593590_1150438|2117899814_1_1351594276_633924");
        connection.setRequestProperty("Host", "z.alimama.com");
        connection.setRequestProperty("Referer", "http://www.weiresearch.com:40080/weiresearch/interestsTag.jsp");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");

        // 建立与服务器的连接，并未发送数据
        connection.connect();

        // 发送数据到服务器并使用Reader读取返回的数据

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"GBK"));

        System.out.println(" ============================= ");
        System.out.println(" Contents of get request ");
        System.out.println(" ============================= ");

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        System.out.println(sb);

        reader.close();
        // 断开连接
        connection.disconnect();

        return sb.toString();
    }

    public List<String> getEmotions(float score) {
        List<String> emotions = new ArrayList<String>();
        if(Math.abs(score)%10000l > 999f){
            emotions.add("emotion-fan");
        }
        if(Math.abs(score)%100000l > 9999f){
            emotions.add("emotion-le");
        }
        if(Math.abs(score)%1000000l > 99999f){
            emotions.add("emotion-nv");
        }
        if(Math.abs(score)%10000000l > 999999f){
            emotions.add("emotion-pa");
        }
        if(Math.abs(score)%100000000l > 9999999f){
            emotions.add("emotion-shang");
        }
        if(Math.abs(score)%1000000000l > 99999999f){
            emotions.add("emotion-yao");
        }
        return emotions;
    }

}

class Keywords {
    public String word;
    public String mention;
    public List<String> emotionClass = new ArrayList<String>();

    public Keywords(String word, String mention, List<String> emotionClass) {
        this.word = word;
        this.mention = mention;
        this.emotionClass = emotionClass;
    }

    public List<String> getEmotionClass() {
        return emotionClass;
    }

    public void setEmotionClass(List<String> emotionClass) {
        this.emotionClass = emotionClass;
    }

    public String getMention() {
        return mention;
    }

    public void setMention(String mention) {
        this.mention = mention;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

}

class Ads {
    public String keyword;
    public String content;

    public Ads(String keyword, String content) {
        this.keyword = keyword;
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

}